import requests
import random
import time
import os
from os import system
import datetime
import sys
import math
from pidModule import writePid
import re
from bs4 import BeautifulSoup
#pip install texttable
from texttable import Texttable

system("title tushareLimit") #给终端命名
max_width=268
os.system("mode con cols="+str(max_width)+" lines=78")#设置控制台尺寸

# 获取当前脚本所在目录路径
#script_dir = os.path.dirname(os.path.realpath(__file__))

pidPath = "tushareLimit.pid"

#涨跌停数
upNum = 0
downNum = 0
#st涨跌停数
stUpNum = 0
stDownNum = 0
#炸板数
zbNum = 0

# 修改舍入方式为四舍五入，解决round 遇5不进的问题
def round_up_down(dst,num = 2):
    dst = float(dst)
    if(dst * pow(10,num+1)%10 == 5):
        ans = math.ceil(dst * pow(10, num)) / pow(10, num)
    else:
        ans = round(dst, num)
    return ans

#字符串获取纯数字
def extract_numbers(text):
    num_str = ''
    # 提取字符串中的数字
    for char in text:
        if char.isnumeric():
            num_str += char
    # 输出匹配结果
    return num_str

#判断数组长度 不足则空格填充
def pad_array_with_spaces(arr, desired_length,str = ' '):
    while len(arr) < desired_length:
        arr.append(str)
    return arr

#倒计时，秒
def countdown(seconds):
    while seconds > 0:
        sec = seconds % 60
        minute = seconds / 60 % 60
        hour = seconds / 60 / 60
        hour = math.floor(hour)  # 去掉小数点，向下取整
        minute = math.floor(minute)  # 去掉小数点，向下取整

        sys.stdout.write('\r' + "距离自动刷新还剩" + str(hour) + "小时" + str(minute) + "分钟" + str(sec) + "秒")
        sys.stdout.flush()
        time.sleep(1)
        seconds -= 1

def get_stock_type(code):
    # 定义不同市场的规则
    shanghai = r'^60[0-9]{4}$'   # 上海A股
    shenzhen = r'^00[0-9]{4}$'   # 深圳A股或者中小企业挂牌公司
    chuangye = r'^30[0-9]{4}$'   # 创业板
    kechuan = r'^68[0-9]{4}$'   # 科创版
    beijiao = r'^82|83|87|88[0-9]{4}$'   #北交所股票代码开头是82、83、87、88,主要以8开头
    
    #返回涨跌幅限制，0.1为10cm，即10%
    if re.match(shanghai, code):
        exchange = ''
    elif re.match(shenzhen, code):
        exchange = ''
    elif re.match(chuangye, code):
        exchange = '创'
    elif re.match(kechuan, code):
        exchange = '科'
    elif re.match(beijiao, code):
        exchange = '北'
    else:
        exchange = ''

    return exchange

def getHTMLText(url):
    try:
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36'}
        r = requests.get(url, headers=headers,timeout=5)
        r.raise_for_status() # 如果状态不是200，引发HTTPError异常
        # print(r.status_code)# 查看状态码
        r.encoding = r.apparent_encoding
        # print('success')
        return r.text
    except Exception as e:
        print(f"异常信息：{str(e)}")
        return "产生异常"

def get_xuangubao_api(api_url):  
    try:
        # 发送GET请求   
        #headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36'}
        # 关闭不必要连接
        requests.DEFAULT_RETRIES = 5
        s = requests.session()
        s.keep_alive = False
        # proxy = {"http": "xxfb.mwr.cn:8080"}
        user_agent_list = [
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36",
            "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
            "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36",
            "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36",
            "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36",
            "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)",
            "Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10.5; en-US; rv:1.9.2.15) Gecko/20110303 Firefox/3.6.15"
        ]
        
        headers = {
            'Origin': 'https://xuangubao.cn',
            'Referer': 'https://xuangubao.cn/dingpan',
            'User-Agent': '',
            'Request Method': 'GET',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'en-US,en;q=0.9',
            'Connection': 'keep-alive',
            'Upgrade-Insecure-Requests': '1'
        }
        #headers['User-Agent'] = random.choice(user_agent_list)
        #response = requests.get(api_url, headers=headers,timeout=5)
        timeout = random.uniform(1, 5)
        response = requests.get(api_url,timeout=timeout)

        # 检查请求是否成功  
        if response.status_code == 200:  
            #随机等待间隔
            time.sleep(random.uniform(0.5, 1))
            # 解析返回的JSON数据  
            data = response.json()  
            return data  
        else:  
            print(f"请求失败，状态码：{response.status_code}")  
            return {}
            exit()
    except Exception as e:
        print(f"异常信息：{str(e)}")
        return {}
        #exit()
    return {}


def getDapanInfo():
    # ——大盘涨跌停数量—— limit_up_count,limit_down_count
    # ——大盘涨跌数量—— rise_count,fall_count
    # ——炸板率—— limit_up_broken_count,limit_up_broken_ratio
    dpList = get_xuangubao_api('https://flash-api.xuangubao.cn/api/market_indicator/line?fields=rise_count,fall_count,limit_up_broken_count,limit_up_broken_ratio,yesterday_limit_up_avg_pcp')
    
    if isinstance(dpList, object) == False or dpList == {} or dpList == []:
        print('大盘数据接口获取失败')
        return False


    dpInfo = dpList["data"][len(dpList["data"])-1]

    zbRatio = round(dpInfo['limit_up_broken_ratio']*100,2)
    zbRatioStr = '低'
    if zbRatio >= 35:
        zbRatioStr = '高'
    elif 30 <= zbRatio < 35 :
        zbRatioStr = '中'


    print("涨跌数比 [ "+str(dpInfo['rise_count'])+":"+str(dpInfo['fall_count'])+" ] * " + 
        "涨跌停比 [ "+str(upNum)+":"+str(downNum)+" ] * " +
        "st涨跌停比 [ "+str(stUpNum)+":"+str(stDownNum)+" ] * " +
        "炸板数: "+str(zbNum)+" * " +
        "炸板率:"+str(zbRatio)+ "%<" + zbRatioStr +"> * 昨日涨停今表现:"+str(round(dpInfo['yesterday_limit_up_avg_pcp']*100,2))+"%"
        )

def getClsList(htmlStr,getNum):
    #获取标题和url
    soup = BeautifulSoup(htmlStr, 'html.parser')
    
    GupiaoList=soup.find_all('div',class_='telegraph-list')
    result=[]
    i = 1
    for gp in GupiaoList:
        #获取的数量
        if i > getNum:
            break

        data={}
        data['title']=gp.text
        #data['url']=gp['href']
        result.append(data)
        content_text = ''
        gupiao_text = ''

        try:
            #输出内容
            content_text = gp.find(class_="telegraph-content-box").getText()
            if str(gp).find('<span class="c-de0422">') != -1:
                #找到了标红的标题
                content_text = "\033[1;31m"+"※"+"\033[0m"+content_text+'\n'
            
            #输出提示的股票
            gupiao_text = gp.find(class_="telegraph-stock-plate-box").getText()
            
        except Exception as e:
            error=e
            #print(f"异常信息：{str(e)}")
            

        if content_text != '':
            print(content_text)
        if gupiao_text != '':
            print("【 "+gupiao_text+" 】")
        if content_text != '' or gupiao_text != '':
            print('') 
            i+=1

        
        #print(data)
    return result

def printTableUpList(url):

    global stUpNum
    global upNum
    stUpNum = 0
    upNum = 0

    apiData=get_xuangubao_api(url)
    if isinstance(apiData, object) == False or apiData == {} or apiData == []:
        print('Zt接口获取数据失败')
        return False

    data = apiData['data']
    # 使用sorted()函数按时间戳排序
    sorted_data = sorted(data, key=lambda x: x['first_limit_up'])
    #print(apiData)


    stored_num = 0
    dayAddNum=0
    dayNum = 0
    hightNum = 0
    twentyCmNum = 0
    regionNum945 = 0
    regionNum1000 = 0
    upList1 = []
    upList2 = []
    upList3 = []
    upList4 = []
    for item in sorted_data:
        if "ST" in item['stock_chi_name'] or "st" in item['stock_chi_name'] :
            stUpNum=stUpNum+1
            continue
        #求出非st的股票数量
        upNum = upNum+1

        if item['limit_up_days'] == 1:
            upList1.append(item)

        if item['limit_up_days'] == 2:
            upList2.append(item)

        if item['limit_up_days'] == 3:
            upList3.append(item)

        if item['limit_up_days'] >=4:
            upList4.append(item)


    # 创建一个Texttable实例
    table1 = Texttable()
    table1.set_chars(['-', '|', '+', '-'])
    table1.set_max_width(max_width)
    # Texttable设置表头
    tableHeader = ["id", "stock_name","surge_reason", "limit_days","limit_info","","id","stock_name","surge_reason", "limit_days","limit_info","","id", "stock_name","surge_reason", "limit_days","limit_info","","id", "stock_name","surge_reason", "limit_days","limit_info"]
    tableHeaderLen = len(tableHeader)
    table1.header(tableHeader)
    add_row = [];
    # 遍历数据并添加到PrettyTable
    if len(upList1) > 0:
        upListNum1 = 0;
        for item in upList1:
            if "ST" in item['stock_chi_name'] or "st" in item['stock_chi_name'] :
                continue;

        
            try:
                surge_reason = (item['surge_reason']['related_plates'][0]['plate_name'])
            except Exception as e:
                error=e
                surge_reason = ''

            stored_num=stored_num+1
            upListNum1=upListNum1+1
            code = extract_numbers(item['symbol'])

            # 将时间戳转换为datetime对象
            first_limit = datetime.datetime.fromtimestamp(item['first_limit_up'])
            last_limit = datetime.datetime.fromtimestamp(item['last_limit_up'])


            hour = first_limit.time().strftime('%H')
            minute = first_limit.time().strftime('%M')
             
            # 使用time模块的strftime方法格式化时分秒
            first_limit = first_limit.time().strftime('%H:%M:%S')
            last_limit = last_limit.time().strftime('%H:%M:%S')

            zhangfu = round(item['change_percent']*100,2)

            stockTypeInfo = ''
            stockType = get_stock_type(code)
            if(stockType != ''):
                stockTypeInfo = "{"+stockType+"}"

            if(stockType == '创' or stockType == '科' or stockType == '北'):
                twentyCmNum = twentyCmNum+1

            #str(item['price'])
            row = [stored_num, str(item['stock_chi_name'])+stockTypeInfo,surge_reason, "["+str(item['limit_up_days'])+"] "+str(round_up_down(item['non_restricted_capital']/100000000))+"Y", str(first_limit)]
            if len(add_row) != 0:
                add_row.append('');
            add_row = add_row + row
            if( len(upList1) == upListNum1 and ( upListNum1%4!=0  ) ):
                add_row = pad_array_with_spaces(add_row,tableHeaderLen, ' ')
            
            if(len(add_row) == tableHeaderLen):
                #print(add_row)
                table1.add_row(add_row)
                add_row = [];

            if item['limit_up_days'] > 1:
                dayAddNum=dayAddNum+1
            else:
                dayNum=dayNum+1

            if int(item['limit_up_days']) > hightNum:
                hightNum=int(item['limit_up_days'])

            if int(hour) == 9 and int(minute) <= 45:
                regionNum945 = regionNum945+1

            if int(hour) == 9 and int(minute) <= 59:
                regionNum1000 = regionNum1000+1
 

    
    if len(upList2) > 0:
        upListNum2 = 0;
        # 创建一个Texttable实例
        table2 = Texttable()
        table2.set_chars(['-', '|', '+', '-'])
        table2.set_max_width(max_width)
        # Texttable设置表头
        #tableHeader = ["id", "stock_name","surge_reason", "limit_days","limit_info","","id","stock_name","surge_reason", "limit_days","limit_info","","id", "stock_name","surge_reason", "limit_days","limit_info","","id", "stock_name","surge_reason", "limit_days","limit_info"]
        #tableHeaderLen = len(tableHeader)
        #table.header(tableHeader)
        add_row = [];
        # 遍历数据并添加到PrettyTable
        for item in upList2:
            if "ST" in item['stock_chi_name'] or "st" in item['stock_chi_name'] :
                continue;

        
            try:
                surge_reason = (item['surge_reason']['related_plates'][0]['plate_name'])
            except Exception as e:
                error=e
                surge_reason = ''

            stored_num=stored_num+1
            upListNum2=upListNum2+1
            code = extract_numbers(item['symbol'])

            # 将时间戳转换为datetime对象
            first_limit = datetime.datetime.fromtimestamp(item['first_limit_up'])
            last_limit = datetime.datetime.fromtimestamp(item['last_limit_up'])


            hour = first_limit.time().strftime('%H')
            minute = first_limit.time().strftime('%M')
             
            # 使用time模块的strftime方法格式化时分秒
            first_limit = first_limit.time().strftime('%H:%M:%S')
            last_limit = last_limit.time().strftime('%H:%M:%S')

            zhangfu = round(item['change_percent']*100,2)

            stockTypeInfo = ''
            stockType = get_stock_type(code)
            if(stockType != ''):
                stockTypeInfo = "{"+stockType+"}"

            if(stockType == '创' or stockType == '科' or stockType == '北'):
                twentyCmNum = twentyCmNum+1

            #str(item['price'])
            row = [stored_num, str(item['stock_chi_name'])+stockTypeInfo,surge_reason, "["+str(item['limit_up_days'])+"] "+str(round_up_down(item['non_restricted_capital']/100000000))+"Y", str(first_limit)]
            if len(add_row) != 0:
                add_row.append('');
            add_row = add_row + row
            if( len(upList2) == upListNum2 and ( upListNum2%4!=0  ) ):
                #print(stored_num)
                add_row = pad_array_with_spaces(add_row,tableHeaderLen, ' ')
            
            if(len(add_row) == tableHeaderLen):
                #print(add_row)
                table2.add_row(add_row)
                add_row = [];

            if item['limit_up_days'] > 1:
                dayAddNum=dayAddNum+1
            else:
                dayNum=dayNum+1

            if int(item['limit_up_days']) > hightNum:
                hightNum=int(item['limit_up_days'])

            if int(hour) == 9 and int(minute) <= 45:
                regionNum945 = regionNum945+1

            if int(hour) == 9 and int(minute) <= 59:
                regionNum1000 = regionNum1000+1
     

    if len(upList3) > 0:
        upListNum3 = 0;
        # 创建一个Texttable实例
        table3 = Texttable()
        table3.set_chars(['-', '|', '+', '-'])
        table3.set_max_width(max_width)
        # Texttable设置表头
        #tableHeader = ["id", "stock_name","surge_reason", "limit_days","limit_info","","id","stock_name","surge_reason", "limit_days","limit_info","","id", "stock_name","surge_reason", "limit_days","limit_info","","id", "stock_name","surge_reason", "limit_days","limit_info"]
        #tableHeaderLen = len(tableHeader)
        #table.header(tableHeader)
        add_row = [];
        # 遍历数据并添加到PrettyTable
        for item in upList3:
            if "ST" in item['stock_chi_name'] or "st" in item['stock_chi_name'] :
                continue;

        
            try:
                surge_reason = (item['surge_reason']['related_plates'][0]['plate_name'])
            except Exception as e:
                error=e
                surge_reason = ''

            stored_num=stored_num+1
            upListNum3=upListNum3+1
            code = extract_numbers(item['symbol'])

            # 将时间戳转换为datetime对象
            first_limit = datetime.datetime.fromtimestamp(item['first_limit_up'])
            last_limit = datetime.datetime.fromtimestamp(item['last_limit_up'])


            hour = first_limit.time().strftime('%H')
            minute = first_limit.time().strftime('%M')
             
            # 使用time模块的strftime方法格式化时分秒
            first_limit = first_limit.time().strftime('%H:%M:%S')
            last_limit = last_limit.time().strftime('%H:%M:%S')

            zhangfu = round(item['change_percent']*100,2)

            stockTypeInfo = ''
            stockType = get_stock_type(code)
            if(stockType != ''):
                stockTypeInfo = "{"+stockType+"}"

            if(stockType == '创' or stockType == '科' or stockType == '北'):
                twentyCmNum = twentyCmNum+1

            #str(item['price'])
            row = [stored_num, str(item['stock_chi_name'])+stockTypeInfo,surge_reason, "["+str(item['limit_up_days'])+"] "+str(round_up_down(item['non_restricted_capital']/100000000))+"Y", str(first_limit)]
            if len(add_row) != 0:
                add_row.append('');
            add_row = add_row + row
            if( len(upList3) == upListNum3 and ( upListNum3%4!=0  ) ):
                add_row = pad_array_with_spaces(add_row,tableHeaderLen, ' ')
            
            if(len(add_row) == tableHeaderLen):
                #print(add_row)
                table3.add_row(add_row)
                add_row = [];

            if item['limit_up_days'] > 1:
                dayAddNum=dayAddNum+1
            else:
                dayNum=dayNum+1

            if int(item['limit_up_days']) > hightNum:
                hightNum=int(item['limit_up_days'])

            if int(hour) == 9 and int(minute) <= 45:
                regionNum945 = regionNum945+1

            if int(hour) == 9 and int(minute) <= 59:
                regionNum1000 = regionNum1000+1
     

    if len(upList4) > 0:
        upListNum4 = 0;
        # 创建一个Texttable实例
        table4 = Texttable()
        table4.set_chars(['-', '|', '+', '-'])
        table4.set_max_width(max_width)
        # Texttable设置表头
        #tableHeader = ["id", "stock_name","surge_reason", "limit_days","limit_info","","id","stock_name","surge_reason", "limit_days","limit_info","","id", "stock_name","surge_reason", "limit_days","limit_info","","id", "stock_name","surge_reason", "limit_days","limit_info"]
        #tableHeaderLen = len(tableHeader)
        #table.header(tableHeader)
        add_row = [];
        # 遍历数据并添加到PrettyTable
        for item in upList4:
            if "ST" in item['stock_chi_name'] or "st" in item['stock_chi_name'] :
                continue;

        
            try:
                surge_reason = (item['surge_reason']['related_plates'][0]['plate_name'])
            except Exception as e:
                error=e
                surge_reason = ''

            stored_num=stored_num+1
            upListNum4=upListNum4+1;
            code = extract_numbers(item['symbol'])

            # 将时间戳转换为datetime对象
            first_limit = datetime.datetime.fromtimestamp(item['first_limit_up'])
            last_limit = datetime.datetime.fromtimestamp(item['last_limit_up'])


            hour = first_limit.time().strftime('%H')
            minute = first_limit.time().strftime('%M')
             
            # 使用time模块的strftime方法格式化时分秒
            first_limit = first_limit.time().strftime('%H:%M:%S')
            last_limit = last_limit.time().strftime('%H:%M:%S')

            zhangfu = round(item['change_percent']*100,2)

            stockTypeInfo = ''
            stockType = get_stock_type(code)
            if(stockType != ''):
                stockTypeInfo = "{"+stockType+"}"

            if(stockType == '创' or stockType == '科' or stockType == '北'):
                twentyCmNum = twentyCmNum+1

            #str(item['price'])
            row = [stored_num, str(item['stock_chi_name'])+stockTypeInfo,surge_reason, "["+str(item['limit_up_days'])+"] "+str(round_up_down(item['non_restricted_capital']/100000000))+"Y", str(first_limit)]
            if len(add_row) != 0:
                add_row.append('');
            add_row = add_row + row
            if( len(upList4) == upListNum4 and ( upListNum4%4!=0  ) ):
                add_row = pad_array_with_spaces(add_row,tableHeaderLen, ' ')
            
            if(len(add_row) == tableHeaderLen):
                #print(add_row)
                table4.add_row(add_row)
                add_row = [];

            if item['limit_up_days'] > 1:
                dayAddNum=dayAddNum+1
            else:
                dayNum=dayNum+1

            if int(item['limit_up_days']) > hightNum:
                hightNum=int(item['limit_up_days'])

            if int(hour) == 9 and int(minute) <= 45:
                regionNum945 = regionNum945+1

            if int(hour) == 9 and int(minute) <= 59:
                regionNum1000 = regionNum1000+1
     

    print(url+" 【 "+"Zt总数量"+str(stored_num)+" 】 【 "+"连续Zt数量："+str(dayAddNum)+" 】 【 "+"首板Zt数量："+str(dayNum)+" 】 【 "+"20cm+数量："+str(twentyCmNum)+" 】 【 "+"9:45数量："+str(regionNum945)+" 】 【 "+"10:00数量："+str(regionNum1000)+" 】 【 "+"Zt空间板："+str(hightNum)+" 】 ")

    if len(upList1) > 0:
         #输出texttable
        print(table1.draw())

    if len(upList2) > 0:
         #输出texttable
        print(table2.draw())

    if len(upList3) > 0:
         #输出texttable
        print(table3.draw())

    if len(upList4) > 0:
         #输出texttable
        print(table4.draw())

def printTableDownList(url):

    global stDownNum
    global downNum
    stDownNum = 0
    downNum = 0

    apiData=get_xuangubao_api(url)
    if isinstance(apiData, object) == False or apiData == {} or apiData == []:
        print('Dt接口获取数据失败')
        return False

    data = apiData['data']

    # 使用sorted()函数按时间戳排序
    sorted_data = sorted(data, key=lambda x: x['first_limit_down'],reverse=False)
    #print(apiData)

    # 创建一个Texttable实例
    table = Texttable()
    table.set_chars(['-', '|', '+', '-'])
    table.set_max_width(max_width)
    # Texttable设置表头
    tableHeader = [ "stock_info","","stock_info","","stock_info","","stock_info","","stock_info","","stock_info","","stock_info","","stock_info","","stock_info","","stock_info"]
    tableHeaderLen = len(tableHeader)
    table.header(tableHeader)

    add_row = [];

    stored_num = 0
    dayAddNum = 0
    dayNum=0
    hightNum = 0
    twentyCmNum = 0
    regionNum945 = 0
    regionNum1000 = 0
    for item in sorted_data:
        if "ST" in item['stock_chi_name'] or "st" in item['stock_chi_name'] :
            stDownNum=stDownNum+1
            continue
        #求出非st的股票数量
        downNum = downNum+1

    # 遍历数据并添加到PrettyTable
    for item in sorted_data:
        if "ST" in item['stock_chi_name'] or "st" in item['stock_chi_name'] :
            continue;
        
        code = extract_numbers(item['symbol'])
        stored_num=stored_num+1

        # 将时间戳转换为datetime对象
        first_limit = datetime.datetime.fromtimestamp(item['first_limit_down'])
        last_limit = datetime.datetime.fromtimestamp(item['last_limit_down'])
         
        hour = first_limit.time().strftime('%H')
        minute = first_limit.time().strftime('%M')

        # 使用time模块的strftime方法格式化时分秒
        first_limit = first_limit.time().strftime('%H:%M:%S')
        last_limit = last_limit.time().strftime('%H:%M:%S')

        zhangfu = round(item['change_percent']*100,2)

        stockType = get_stock_type(code)

        if(stockType == '创' or stockType == '科' or stockType == '北'):
            twentyCmNum = twentyCmNum+1

        row = [str(item['stock_chi_name']) +  " ["+str(item['limit_down_days'])+"] "+str(round_up_down(item['non_restricted_capital']/100000000))+"Y"]
        if len(add_row) != 0:
            add_row.append('');
        add_row = add_row + row
        if( downNum == stored_num and ( stored_num%10!=0  ) ):
            add_row = pad_array_with_spaces(add_row,tableHeaderLen, ' ')
        
        if(len(add_row) == tableHeaderLen):
            #print(add_row)
            table.add_row(add_row)
            add_row = [];

        if item['limit_down_days'] > 1:
            dayAddNum=dayAddNum+1
        else:
            dayNum=dayNum+1


        if int(item['limit_down_days']) > hightNum:
            hightNum=int(item['limit_down_days'])

        if int(hour) == 9 and int(minute) <= 45:
            regionNum945 = regionNum945+1

        if int(hour) == 9 and int(minute) <= 59:
            regionNum1000 = regionNum1000+1
        
        
        #exit()
 
    print(url+" 【 "+"Dt总数量"+str(stored_num)+" 】 【 "+"连续Dt数量："+str(dayAddNum)+" 】 【 "+"首板Dt数量："+str(dayNum)+" 】 【 "+"20cm+数量："+str(twentyCmNum)+" 】 【 "+"9:45数量："+str(regionNum945)+" 】 【 "+"10:00数量："+str(regionNum1000)+" 】 【 "+"Dt空间板："+str(hightNum)+" 】 ")
    #输出texttable
    print(table.draw())


def printTableZbList(url):
    global zbNum
    zbNum = 0
    apiData=get_xuangubao_api(url)
    if isinstance(apiData, object) == False or apiData == {} or apiData == []:
        print('Zb接口获取数据失败')
        return False
    data = apiData['data']

    # 使用sorted()函数按时间戳排序
    sorted_data = sorted(data, key=lambda x: x['first_limit_up'],reverse=False)
    #print(apiData)

    # 创建一个Texttable实例
    table = Texttable()
    table.set_chars(['-', '|', '+', '-'])
    table.set_max_width(max_width+6)
    # Texttable设置表头
    tableHeader = [ "stock_info","","stock_info","","stock_info","","stock_info","","stock_info","","stock_info","","stock_info","","stock_info"]
    tableHeaderLen = len(tableHeader)
    table.header(tableHeader)

    add_row = [];

    stored_num = 0
    dayAddNum = 0
    dayNum=0
    total_num = 0
    hightNum = 0
    twentyCmNum = 0
    regionNum945 = 0
    regionNum1000 = 0
    for item in sorted_data:
        if "ST" in item['stock_chi_name'] or "st" in item['stock_chi_name'] :
            continue
        #求出非st的股票数量
        total_num = total_num+1

    # 遍历数据并添加到PrettyTable
    for item in sorted_data:
        if "ST" in item['stock_chi_name'] or "st" in item['stock_chi_name'] :
            continue;

        try:
            surge_reason = (item['surge_reason']['related_plates'][0]['plate_name'])
        except Exception as e:
            error=e
            surge_reason = ''

        stored_num=stored_num+1
        
        code = extract_numbers(item['symbol'])

        # 将时间戳转换为datetime对象
        first_limit = datetime.datetime.fromtimestamp(item['first_limit_down'])
        last_limit = datetime.datetime.fromtimestamp(item['last_limit_down'])
         
        hour = first_limit.time().strftime('%H')
        minute = first_limit.time().strftime('%M')

        # 使用time模块的strftime方法格式化时分秒
        first_limit = first_limit.time().strftime('%H:%M:%S')
        last_limit = last_limit.time().strftime('%H:%M:%S')



        zhangfu = round(item['change_percent']*100,2)

        stockType = get_stock_type(code)
        if(stockType == '创' or stockType == '科' or stockType == '北'):
            twentyCmNum = twentyCmNum+1

        if(zhangfu > 0):
            zhangfu = " ["+str(zhangfu)+"%] "
        else:
            zhangfu = " <"+str(zhangfu)+"%> "
        row = [str(item['stock_chi_name'])+zhangfu + surge_reason]
        if len(add_row) != 0:
            add_row.append('');
        add_row = add_row + row
        if( total_num == stored_num and ( stored_num%8!=0  ) ):
            add_row = pad_array_with_spaces(add_row,tableHeaderLen, ' ')
        
        if(len(add_row) == tableHeaderLen):
            #print(add_row)
            table.add_row(add_row)
            add_row = [];

        #exit()
    zbNum = stored_num
    print(url+" 【 "+"Zb总数量"+str(stored_num)+" 】 【 "+"20cm+数量："+str(twentyCmNum)+" 】 ")
    #输出texttable
    print(table.draw())


def main():
    #抓取的选股宝网页地址：https://xuangubao.cn/dingpan
    #https://codingchangeworld.com/%E7%BD%91%E7%BB%9C%E7%88%AC%E8%99%AB/ry/detail_article/5211713346760
    urlZb =f'https://flash-api.xuangubao.cn/api/pool/detail?pool_name=limit_up_broken'
    printTableZbList(urlZb)

    urlDown =f'https://flash-api.xuangubao.cn/api/pool/detail?pool_name=limit_down'
    printTableDownList(urlDown)
    
    print('')
    
    urlUp =f'https://flash-api.xuangubao.cn/api/pool/detail?pool_name=limit_up'
    printTableUpList(urlUp)
    getDapanInfo()
        
if __name__ == '__main__':
    # 计算明天的日期
    tomorrow = datetime.datetime.now() + datetime.timedelta(days=1)
    #写入进程pid
    writePid(pidPath)
    print("当前时间："+ str(datetime.datetime.now())) 
    todayTime = datetime.date.today()
    while True:
        # 获取当前时间
        now = datetime.datetime.now()
        nowTimeInt = int(now.strftime("%H%M"))
        #开盘时间
        specified_time = now
        seconds_difference = 0
        if  nowTimeInt < 925:
            specified_time = datetime.datetime(todayTime.year, todayTime.month, todayTime.day, 9, 25, 0)
        elif 1130 <= nowTimeInt < 1300:
            specified_time = datetime.datetime(todayTime.year, todayTime.month, todayTime.day, 13, 00, 0)
        elif 1500 <= nowTimeInt < 2358:
            specified_time = datetime.datetime(tomorrow.year, tomorrow.month, tomorrow.day, 9, 15, 0)

        # 计算时间差
        delta = specified_time - now
        seconds_difference = int(delta.total_seconds())

        
        os.system("cls")   # 清屏操作

        url =f'https://www.cls.cn/telegraph'
        html=getHTMLText(url)
        ClsInfo=getClsList(html,5)

        if nowTimeInt >= 925:
            #避免没数据导致出错退出
            main()

        #休市时间，避免无必要的刷新
        if seconds_difference > 0:
            #倒计时
            sleepTime = random.uniform(120, 180)
            countdown(sleepTime)
        else:
            if nowTimeInt < 925:
                sleepTime = random.uniform(10, 15)
                countdown(sleepTime)
            elif nowTimeInt < 1000:
                sleepTime = random.uniform(15, 20)
                time.sleep(sleepTime)
            else:
                sleepTime = random.uniform(20, 30)
                time.sleep(sleepTime)
    


